<?php

namespace Xrfg\Api\Trading\Home\Console\Commands;

use Exception;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CNY extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cny';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '币种对人民币价格';

    protected $isCacheUsdt = false;

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $coinNames = ['usdt', 'btc'];
        $http = new Client();

        try {
            // 从OK交易所获取行情数据
            $response = $http->get('https://www.okex.com/v2/market/index/tickerAll', ['verify' => false]);
            $data = json_decode($response->getBody()->getContents(), true)['data'];
            collect($data)->whereIn('coinName', $coinNames)
                ->each(function ($item) {
                    if (!$this->isCacheUsdt) {
                        Cache::forever('ticker:okex.com:otc:usdt', [
                            'coin_name' => 'usdt',
                            'price_cny' => bcmul(1, $item['usdCnyRate'], 3),
                            'change_percent' => 0,
                        ]);
                        $this->info('usdt:'.$item['usdCnyRate']);
                        $this->isCacheUsdt = true;
                    }

                    Cache::forever('ticker:okex.com:otc:'.$item['coinName'], [
                        'coin_name' => $item['coinName'],
                        'price_cny' => bcmul(strval($item['last']), strval($item['usdCnyRate']), 3),
                        'change_percent' => $item['changePercent'],
                    ]);
                    $this->info($item['coinName'].':'.$item['last'] * $item['usdCnyRate']);
                });
        } catch (Exception $exception) {
            Log::error($exception);

            return;
        }
    }
}
